<template>
  <div>
    <a-card class="general-card" :bordered="false">
      <a-form ref="formRef" :model="form">
        <h4>商品信息</h4>
        <a-button type="outline" @click="openSkuList" class="changGoods">
          选择商品
        </a-button>
        <PickTablePage
          ref="tablePageRef"
          :columns="columns"
          :dataList="form.promotionGoodsList"
          :enablePagination="false"
          :bordered="true"
        >
          <template #settlementPrice="{ rowIndex }">
            <a-input-number
              v-model="form.promotionGoodsList[rowIndex].settlementPrice"
              class="input-demo"
              :min="0"
            />
          </template>
          <template #lowestPrice="{ rowIndex }">
            <a-input-number
              v-model="form.promotionGoodsList[rowIndex].lowestPrice"
              class="input-demo"
              :min="0"
            />
          </template>
          <template #highestPrice="{ rowIndex }">
            <a-input-number
              v-model="form.promotionGoodsList[rowIndex].highestPrice"
              class="input-demo"
              :min="0"
            />
          </template>
          <template #stock="{ rowIndex }">
            <a-input-number
              v-model="form.promotionGoodsList[rowIndex].stock"
              class="input-demo"
              :min="0"
            />
          </template>
          <template #action="{ rowIndex }">
            <a-button type="text" status="danger" @click="delGoods(rowIndex)"
              >删除</a-button
            >
          </template>
        </PickTablePage>
        <div style="margin-top: 15px">
          <div>
            活动时间： &nbsp;
            <a-range-picker
              v-model="form.rangeTime"
              show-time
              style="width: 354px; margin-bottom: 20px"
            />
          </div>
        </div>
        <div>
          <a-button style="margin-right: 5px" @click="closeCurrentPage"
            >返回</a-button
          >
          <a-button type="primary" @click="handleSubmit">提交</a-button>
        </div>
      </a-form>
    </a-card>
    <skuselect
      ref="skuSelect"
      @change="changSkuList"
      :goodsOrSku="true"
      :apiParams="apiParams"
      :defaultGoodsSelectedList="form.promotionGoodsList"
    ></skuselect>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from 'vue';
import { PickTablePage } from '@pickmall/ui-v3-components'
import skuselect from '@/components/goods-sku-selector/index.vue';
import { Message } from '@arco-design/web-vue';
import { money } from '@/utils/filters';
import { saveKanJiaActivityGoods } from '@/api/promotion';
import { useRouter } from 'vue-router';
import { dayFormatHHssMM } from '@/utils/filters';

const router = useRouter();
const form = ref({
  promotionGoodsList: [],
  rangeTime: '',
}) as any;
const apiParams = {
  marketEnable: 'UPPER',
  authFlag: 'PASS',
};
const checkResult = ref<boolean>(true);
const skuSelect = ref(null) as any; // 商品选择器

const columns: any = [
  {
    title: '商品名称',
    dataIndex: 'goodsName',
  },
  {
    title: '商品价格',
    dataIndex: 'price',
    currency: true,
  },
  {
    title: '库存',
    dataIndex: 'quantity',
  },
  {
    title: '结算价格',
    dataIndex: 'settlementPrice',
    slot: true,
    slotTemplate: 'settlementPrice',
    tooltip: 'none',
  },
  {
    title: '最低砍',
    dataIndex: 'lowestPrice',
    slot: true,
    slotTemplate: 'lowestPrice',
    tooltip: 'none',
  },
  {
    title: '最高砍',
    dataIndex: 'highestPrice',
    slot: true,
    slotTemplate: 'highestPrice',
    tooltip: 'none',
  },
  {
    title: '活动库存',
    dataIndex: 'stock',
    slot: true,
    slotTemplate: 'stock',
    tooltip: 'none',
  },
  {
    title: '操作',
    dataIndex: 'action',
    slot: true,
    slotTemplate: 'action',
  },
];
// 选择商品
const openSkuList = () => {
  skuSelect.value.modalData.visible = true;
};
// 选择的商品
const changSkuList = (val: any) => {
  const list: any = [];
  val.forEach((e: any) => {
    list.push({
      settlementPrice: e.settlementPrice || 0,
      purchasePrice: 0,
      lowestPrice: e.lowestPrice || 0,
      highestPrice: e.highestPrice || 0,
      stock: e.stock || 0,
      goodsName: e.goodsName,
      price: e.price,
      originalPrice: e.price,
      quantity: e.quantity,
      storeId: e.storeId,
      storeName: e.storeName,
      skuId: e.id,
    });
  });
  form.value.promotionGoodsList.push(...list);
};
// 删除
const delGoods = (index: any) => {
  form.value.promotionGoodsList.splice(index, 1);
};
// 提交
const handleSubmit = () => {
  checkResult.value = true;
  if (form.value.rangeTime.length <= 0) {
    Message.warning('请选择活动时间');
    return;
  }
  const params = JSON.parse(JSON.stringify(form.value));

  params.startTime = dayFormatHHssMM(form.value.rangeTime[0]);
  params.endTime = dayFormatHHssMM(form.value.rangeTime[1]);

  // 如果添加活动的时候选择了商品 则对选择的商品参数做一些校验
  if (form.value.promotionGoodsList.length > 0) {
    form.value.promotionGoodsList.forEach((res: any) => {
      // 校验库存参数
      if (res.stock <= 0 || res.stock > res.quantity) {
        checkResult.value = false;
        Message.error('活动库存不能为0且不能超过商品库存');
        return;
      }
      // 结算价格金额格式校验
      if (!money.test(res.settlementPrice)) {
        checkResult.value = false;
        Message.error('结算价格金额格式不正确');
        return;
      }
      // 结算价格金额格式校验
      if (res.settlementPrice < 0 || res.settlementPrice > res.price) {
        checkResult.value = false;
        Message.error('结算价格金额不能为0且不能超过商品价格');
        return;
      }
      // 最高砍价校验
      if (!money.test(res.highestPrice)) {
        checkResult.value = false;
        Message.error('最高可砍金额格式错误');
        return;
      }
      // 最低砍价校验
      if (!money.test(res.lowestPrice)) {
        checkResult.value = false;
        Message.error('最低可砍金额格式错误');
        return;
      }
      if (res.highestPrice <= 0 || res.highestPrice > res.price) {
        checkResult.value = false;
        Message.error('最高可砍金额不能为0且不能超过商品价格');
        return;
      }
      if (res.lowestPrice <= 0 || res.lowestPrice > res.price) {
        checkResult.value = false;
        Message.error('最低可砍金额不能为0');
        return;
      }
      // 校验最高最低砍价金额
      if (res.lowestPrice + 0 > res.highestPrice + 0) {
        checkResult.value = false;
        Message.error('最低砍价金额不能大于最高砍价金额');
        return;
      }
    });
    if (!checkResult.value) {
      return;
    }
    form.value.rangeTime = null;
    saveKanJiaActivityGoods(params).then((res: any) => {
      if (res.data.success) {
        Message.success('砍价活动添加成功');
        router.push({ name: 'bargain-activity' });
      }
    });
  }
};
// 返回
const closeCurrentPage = () => {
  router.push({ name: 'bargain-activity' });
};
</script>

<style lang="less" scoped>
h4 {
  margin-bottom: 10px;
  padding: 0 10px;
  border: 1px solid #ddd;
  background-color: #f8f8f8;
  font-weight: bold;
  color: #333;
  font-size: 14px;
  line-height: 40px;
  text-align: left;
}

.describe {
  font-size: 12px;
  margin-left: 10px;
  color: #999;
}

.effectiveDays {
  font-size: 12px;
  color: #999;

  > * {
    margin: 0 4px;
  }
}

.tips {
  font-size: 12px;
  color: #999;
}

.changGoods {
  margin: 0 20px 20px 20px;
  width: 8%;
}
</style>
